from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

from Config.config import getConfig
from common.config_log import Logger
import time
import sys
logger = Logger().log()

class BaseDriver(object):
    logger = Logger().log()
    def __init__(self, driver):
        self.driver = driver


    # 打开url网址
    def get_url(self):
        # self.driver.get("https://training-demo.forensix.cn/")
        url = getConfig("base_url", "training_url")
        self.driver.get(url)
        self.driver.implicitly_wait(10)
        self.driver.maximize_window()


    # 关闭driver与浏览器
    def quit_webdriver(self):
        self.driver.quit()
        logger.info("关闭浏览器")

    def find_ele(self, *locator:tuple):
        try:
            ele = self.driver.find_element(*locator)
            return ele
        except Exception as e:
            logger.error("没有找到{}元素".format(locator[1]))
            raise Exception


    def find_eles(self, *locator):
        try:
            ele = self.driver.find_elements(*locator)
            return ele
        except Exception as e:
            logger.error("没有找到{}元素".format(locator[1]))
            raise Exception

    def Click(self, ele):
        try:
            ele.click()
        except Exception as e:
            logger.error("点击{}元素失败".format(ele))
            raise e


    def Sendkeys(self, ele, text):
        try:
            ele.send_keys(text)
        except Exception as e:
            logger.error("元素{}输入{}失败".format(ele,text))

    def Clearinput(self, ele):
        try:
            ele.clear()
        except Exception as e:
            logger.error("输入框{}清空失败".format(ele))
            raise Exception("输入框{}清空失败".format(ele))


    def Clearandsend(self, ele, text):
        self.Clearinput(ele)
        self.Sendkeys(ele, text)

    def move_ele(self, ele):
        try:
            ActionChains(self.driver).move_to_element(ele).perform()
        except Exception:
            logger.error("移动到元素失败")
            raise Exception


    # 截图
    def screenshot(self):
        try:
            testcase_name = sys._getframe().f_back.f_code.co_name
            self.driver.save_screenshot(r'D:\pythoncode\trainning\picture\{0}--{1}'.format(testcase_name, time.strftime("%Y-%m-%d %H-%M-%S"))+'.png')
            logger.info("截图成功")
        except Exception:
            logger.error("截图失败")
            raise Exception
